//
//  CoreDataViewController.swift
//  SwiftDemo
//
//  Created by hfzhangzhang on 2018/7/18.
//  Copyright © 2018年 hfzhangzhang. All rights reserved.
//

import UIKit
import CoreData

class CoreDataViewController: UIViewController {
    
    let addBtn:UIButton = {
        let addBtn = UIButton.init(type: UIButtonType.custom)
        addBtn.frame = CGRect(x: 10, y: 10, width: 50, height: 20)
        addBtn.backgroundColor = UIColor.blue;
        addBtn.setTitle("添加", for: UIControlState.normal)
        addBtn.addTarget(self, action:#selector(insertData), for: UIControlEvents.touchUpInside)
        return addBtn;
    }()
    let tableView:UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 30, width: kscreenW, height: kscreenW-50), style: UITableViewStyle.grouped)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CoreDataViewCell")
        return tableView;
    }()
    
    var dataArr = Array<NSManagedObject>();
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.view.addSubview(addBtn)
        self.view.addSubview(tableView)
    }

    @objc func insertData() {
         //步骤一：获取总代理和托管对象总管
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedObectContext = appDelegate.persistentContainer.viewContext
        //步骤二：建立一个entity
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: managedObectContext)
        let student = NSManagedObject(entity: entity!, insertInto: managedObectContext)
        //步骤三：保存值
        student.setValue("zhangzhang", forKey: "name")
       // 步骤四：保存entity到托管对象中
        appDelegate.saveContext()
        self.dataArr.append(student);
        
        self.tableView.reloadData()
        
    }
    
    @objc func getLocalData() {
        //步骤一：获取总代理和托管对象总管
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedObectContext = appDelegate.persistentContainer.viewContext
        
        //步骤二：建立一个获取的请求
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
        
        //步骤三：执行请求
        do {
            let fetchedResults = try managedObectContext.fetch(fetchRequest) as? [NSManagedObject]
            if let results = fetchedResults {
                datas.removeAll()
                for result in results {
                    guard let user = translateData(from: result) else { return }
                    datas.append(user)
                }
                
                tableView.reloadData()
            }
            
        } catch  {
            fatalError("获取失败")
        }
        
    }

}

extension CoreDataViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CoreDataViewCell", for: indexPath)
        let model:Student = self.dataArr[indexPath.row] as! Student;
        cell.textLabel!.text = model.name;
        return cell;
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
}
